package elasticsearch

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"goods_srv/goodsclient"
	"goods_srv/models"
	"log"
	"strconv"
	"sync"
)

// 将商品添加同步到ES
func SyncGoodsEs() {
	var wg sync.WaitGroup
	var good models.Goods
	goodsList, _ := good.GetGoodsList(1, 5)

	for _, goods := range goodsList {
		wg.Add(1)

		go func(goods *models.Goods) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(goods)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(goods.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(goods)
	}
	wg.Wait()
}

// 获取ES
func GetGoodsEs(keyword string) (goodsList []*goodsclient.GetGoodsItem) {
	// 3. Search for the indexed documents
	//
	// Build the request body.
	var buf bytes.Buffer
	var query map[string]interface{}
	if keyword != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"goods_title": keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := Es.Search(
		Es.Search.WithContext(context.Background()),
		Es.Search.WithIndex("goods"),
		Es.Search.WithBody(&buf),
		Es.Search.WithTrackTotalHits(true),
		Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	var r map[string]interface{}
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}

	// Print the ID and document source for each hit.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})

		userId := source["userId"].(float64)
		goodsId := source["ID"].(float64)
		goodsTitle := source["goodsTitle"].(string)
		goodsPrice := source["goodsPrice"].(float64)
		goodsStock := source["goodsStock"].(float64)
		status := source["status"].(float64)
		goodsList = append(goodsList, &goodsclient.GetGoodsItem{
			UserId:     int64(userId),
			GoodsId:    int64(goodsId),
			GoodsTitle: goodsTitle,
			GoodsPrice: float32(goodsPrice),
			GoodsStock: int64(goodsStock),
			Status:     int64(status),
		})
	}
	return
}
